package com.lyandwc.lw_bbs.security.handler;

import com.lyandwc.lw_bbs.entity.User;
import com.lyandwc.lw_bbs.security.entity.UserAuthDetails;
import com.lyandwc.lw_bbs.security.utils.JWTUtils;
import com.lyandwc.lw_bbs.utils.ResponseUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.security.core.Authentication;
import org.springframework.security.web.authentication.AuthenticationSuccessHandler;
import org.springframework.stereotype.Component;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

@Component
public class UserLoginSuccessHandler implements AuthenticationSuccessHandler {
    @Override
    public void onAuthenticationSuccess(HttpServletRequest request, HttpServletResponse response, Authentication authentication) throws IOException, ServletException {
        UserAuthDetails userAuthDetails = (UserAuthDetails) authentication.getPrincipal();
        String token = JWTUtils.createToken(userAuthDetails);

        User user = new User();
        BeanUtils.copyProperties(userAuthDetails, user);
        user.setToken(token);
        ResponseUtils.response(response, 200, "登陆成功", user);
    }
}
